package com.tarena.lbs.content.service.impl;


import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.BasePageQuery;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.basic.api.UserGroupApi;
import com.tarena.lbs.common.content.constance.Const;
import com.tarena.lbs.common.content.enums.ArticeActionEnum;
import com.tarena.lbs.common.content.enums.ContentResultEnum;
import com.tarena.lbs.common.passport.enums.Roles;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.common.security.utils.LbsSecurityContenxt;
import com.tarena.lbs.content.mapper.ArticleCategoryMapper;
import com.tarena.lbs.content.mapper.ArticleContentMapper;
import com.tarena.lbs.content.repository.ContentRepository;
import com.tarena.lbs.content.service.ArticleService;
import com.tarena.lbs.marketing.api.MarketingApi;
import com.tarena.lbs.message.api.TriggerMessageApi;
import com.tarena.lbs.pojo.basic.vo.BusinessVO;
import com.tarena.lbs.pojo.basic.vo.UserVO;
import com.tarena.lbs.pojo.content.dos.ArticleCategory;
import com.tarena.lbs.pojo.content.dto.ArticleActionDTO;
import com.tarena.lbs.pojo.content.dto.ArticleActionPageResultDTO;
import com.tarena.lbs.pojo.content.dto.ArticleContentDTO;
import com.tarena.lbs.pojo.content.param.ArticleActionParam;
import com.tarena.lbs.pojo.content.param.ArticleContentParam;
import com.tarena.lbs.pojo.content.query.ArticleQuery;
import com.tarena.lbs.pojo.message.param.RegisterTriggerMessageParam;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.GeoDistanceQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.collapse.CollapseBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

@Service
@Slf4j
public class ArticleServiceImpl implements ArticleService {
    @Resource
    private ArticleContentMapper articleContentMapper;
    @Resource
    private RestHighLevelClient client;
    @Resource
    private UserGroupApi userGroupApi;

    @Resource
    private MarketingApi marketingRpcApi;

    @Resource
    private TriggerMessageApi triggerMessageApi;

    @Resource
    private ArticleCategoryMapper articleCategoryMapper;

    @Override
    public void insert(ArticleContentParam articleContentParam) {

        ArticleCategory articleCategory = articleCategoryMapper.selectByPrimaryKey(articleContentParam.getArticleCategoryId());
        articleContentParam.setArticleCategory(articleCategory == null ? "" : articleCategory.getCategoryName());

        //根据参数映射，往es中插入数据
        Date date = new Date();
        Map map = JSON.parseObject(JSON.toJSONString(articleContentParam), Map.class);
        map.put("createTime", DateUtil.format(date, DatePattern.NORM_DATETIME_FORMAT));
        map.put("updateTime", DateUtil.format(date, DatePattern.NORM_DATETIME_FORMAT));
        map.put("location", articleContentParam.getLatitude() + "," + articleContentParam.getLongitude());

        //todo 获取当前登录用户Id
        UserPrinciple loginUser = LbsSecurityContenxt.getLoginToken();
        if (loginUser != null) {
            if (Roles.SHOP.equals(loginUser.getRole())) {
                BusinessVO businessVO = userGroupApi.getBusinessInfoByAdminId(loginUser.getId());
                map.put("userId", businessVO.getId());
            } else {
                map.put("userId", loginUser.getId());
            }
        }
        //前台发表文章的时候记录下最新的活动ID
        if(articleContentParam.getSource() == 1) {
            map.put("activityId",marketingRpcApi.getActivityByStoreId(articleContentParam.getShopId()));
        }
        IndexRequest indexRequest = new IndexRequest(Const.CONTENT_INDEX_DATABASE_NAME).id(UUID.randomUUID().toString().replaceAll("-", ""));
        indexRequest.source(map);
        try {
            client.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("ArticleServiceImpl.insert es插入失败：", e.getMessage());
            throw new RuntimeException(e);
        }

    }

    @Override
    public void delete(String id) throws BusinessException {
        //查询es数据库，check数据是否存在
        ArticleContentDTO articleContentDTO = get(id);
        if (articleContentDTO == null) {
            throw new BusinessException(ContentResultEnum.DATA_NOT_FIND);
        }

        //存在的情况下，从es中删除数据
        DeleteRequest deleteRequest = new DeleteRequest(Const.CONTENT_INDEX_DATABASE_NAME, id);
        try {
            client.delete(deleteRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public ArticleContentDTO get(String id) throws BusinessException {
        log.info("ArticleServiceImpl get id={}",id);
        //从es中根据id获取数据
        GetRequest getRequest = new GetRequest(Const.CONTENT_INDEX_DATABASE_NAME, id);
        GetResponse getResponse = null;
        try {
            getResponse = client.get(getRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new BusinessException(ContentResultEnum.DATA_NOT_FIND);
        }

        //返回数据封装
        Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();
        ArticleContentDTO articleContentDTO = JSON.parseObject(JSON.toJSONString(sourceAsMap), ArticleContentDTO.class);
        articleContentDTO.setId(getResponse.getId());
        //查询用户头像和名称，建议采用list一次查询
        if (articleContentDTO.getSource() == 1) {
            UserVO userVO = userGroupApi.getUser(articleContentDTO.getUserId());
            articleContentDTO.setUserName(userVO.getUserName());
            articleContentDTO.setUserPic(userVO.getUserNickPicture());
        } else {
            BusinessVO busiStoreVO = userGroupApi.businessDetail(articleContentDTO.getUserId());
            if (!ObjectUtils.isEmpty(busiStoreVO)){
                articleContentDTO.setUserName(busiStoreVO.getBusinessName());
                articleContentDTO.setUserPic(busiStoreVO.getBusinessLogo());
            }
        }
        return articleContentDTO;
    }

    @Override
    public void action(ArticleActionParam articleActionParam) throws BusinessException {
        String id = articleActionParam.getId();
        GetRequest getRequest = new GetRequest(Const.CONTENT_INDEX_DATABASE_NAME, id);
        GetResponse getResponse = null;
        try {
            getResponse = client.get(getRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new BusinessException(ContentResultEnum.DATA_NOT_FIND);
        }
        Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();
        Integer action = articleActionParam.getAction();

        //文章点赞、访问、收藏，根据前端传入的动作，来确定是点赞、访问、收藏
        ArticleContentDTO articleContentDTO = get(id);
        String field = ArticeActionEnum.getMsgByCode(action);
        //如果是第一次点赞，该count就设置为1，如果不是累加1
        Object o = sourceAsMap.get(field);
        int count = 0;
        if (field.equals(ArticeActionEnum.LIKE.getMsg())) {
            count = articleContentDTO.getLikeCount() == null ? 0 : articleContentDTO.getLikeCount();
        } else if (field.equals(ArticeActionEnum.FAVORITE.getMsg())) {
            count = articleContentDTO.getFavoriteCount() == null ? 0 : articleContentDTO.getFavoriteCount();
        }
        if (o != null) {
            count = count + 1;
        }
        sourceAsMap.put(field, count);

        //更新es
        UpdateRequest updateRequest = new UpdateRequest(Const.CONTENT_INDEX_DATABASE_NAME, id);
        updateRequest.doc(sourceAsMap);
        try {
            client.update(updateRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }


    @Override
    public void update(ArticleContentParam articleContentParam) throws BusinessException {
        //update mysql
        /*ArticleContent articleContent = new ArticleContent();
        BeanUtils.copyProperties(articleContentParam, articleContent);
        Date date = new Date();
        articleContent.setUpdateTime(date);
        articleContentMapper.updateByPrimaryKeySelective(articleContent);*/

        //查询es数据库，check数据是否存在
        ArticleContentDTO articleContentDTO = get(articleContentParam.getId());
        if (articleContentDTO == null) {
            throw new BusinessException(ContentResultEnum.DATA_NOT_FIND);
        }

        //更新es
        UpdateRequest updateRequest = new UpdateRequest(Const.CONTENT_INDEX_DATABASE_NAME, articleContentParam.getId());
        Map map = JSON.parseObject(JSON.toJSONString(articleContentParam), Map.class);
        if (!StringUtils.isEmpty(articleContentParam.getLongitude()) && !StringUtils.isEmpty(articleContentParam.getLatitude())) {
            map.put("location", articleContentParam.getLatitude() + "," + articleContentParam.getLongitude());
        }
        updateRequest.doc(map);
        try {
            client.update(updateRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public HashSet<String> getArticleLabel(ArticleQuery articleQuery) {
        HashSet<String> articleLabelSet = new HashSet<>();
        //构造查询条件
        SearchRequest searchRequest = new SearchRequest(Const.CONTENT_INDEX_DATABASE_NAME);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //基于地理位置
        GeoPoint geoPoint = new GeoPoint(Double.parseDouble(articleQuery.getLatitude()), Double.parseDouble(articleQuery.getLongitude()));
        GeoDistanceQueryBuilder geoDistanceQueryBuilder =
            QueryBuilders.geoDistanceQuery("location")
                //距离 500KM
                .distance(500D, DistanceUnit.KILOMETERS)
                //坐标
                .point(geoPoint);
        boolQueryBuilder.must(geoDistanceQueryBuilder);

        //指定distinct字段
        CollapseBuilder collapseBuilder = new CollapseBuilder("articleLabel");
        searchSourceBuilder.query(boolQueryBuilder).collapse(collapseBuilder).size(20);
        searchRequest.source(searchSourceBuilder);
        SearchResponse reponse = null;
        try {
            reponse = client.search(searchRequest, RequestOptions.DEFAULT);
            for (SearchHit searchHit : reponse.getHits().getHits()) {
                articleLabelSet.add(searchHit.getFields().get("articleLabel").getValue());
            }
            return articleLabelSet;
        }  catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public PageResult<ArticleContentDTO> list(ArticleQuery articleQuery) {
        //todo redis topN ，当前是访客的情况下，直接从redis中获取数据
        //构造查询条件
        SearchRequest searchRequest = new SearchRequest(Const.CONTENT_INDEX_DATABASE_NAME);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        //条件查询，条件拼接
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        Date updateStartTime = articleQuery.getUpdateStartTime();
        Date updateEndTime = articleQuery.getUpdateEndTime();
        Integer articleCategoryId = articleQuery.getArticleCategoryId();
        String articleTitle = articleQuery.getArticleTitle();
        Integer activityId = articleQuery.getActivityId();
        List<Integer> articleStatusList = articleQuery.getArticleStatus();
        Integer source = articleQuery.getSource();
        if (updateStartTime != null) {
            String format = DateUtil.format(updateStartTime, "yyyy-MM-dd HH:mm:ss");
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("updateTime").gte(format));
        }
        if (updateEndTime != null) {
            String format = DateUtil.format(updateStartTime, "yyyy-MM-dd HH:mm:ss");
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("updateTime").lte(format));
        }
        if (articleCategoryId != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("articleCategoryId", articleCategoryId));
        }
        if (StringUtils.isNotBlank(articleTitle)) {
            boolQueryBuilder.filter(QueryBuilders.matchQuery("articleTitle", articleTitle));
        }
        if (activityId != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("activityId", activityId));
        }
        if (StringUtils.isNotBlank(articleQuery.getArticleLabel())) {
            boolQueryBuilder.filter(QueryBuilders.matchQuery("articleLabel", articleQuery.getArticleLabel()));
        }
        if (!CollectionUtils.isEmpty(articleStatusList)) {
            BoolQueryBuilder innerBoolQuery = QueryBuilders.boolQuery();
            for (Integer status : articleStatusList) {
                innerBoolQuery.should(QueryBuilders.termQuery("articleStatus", status));
            }
            boolQueryBuilder.must(innerBoolQuery);
        }

        if (source != null) {
            //1==代表前台查询   2==代表后台查询
            if (source != null && 1 == source.intValue()) {
                if(articleQuery.getUserId() != null) {
                    boolQueryBuilder.must(QueryBuilders.termQuery("userId", articleQuery.getUserId()));
                }
                boolQueryBuilder.filter(QueryBuilders.termQuery("articleStatus", 1));
                //前台查询，需要从redis中获取偏好，根据偏好推荐，并且基于地理位置
                String latitude = articleQuery.getLatitude();
                String longitude = articleQuery.getLongitude();
                if (latitude != null && longitude != null) {
                    //todo 从redis获取偏好

                    //基于地理位置
                    GeoPoint geoPoint = new GeoPoint(Double.parseDouble(latitude), Double.parseDouble(longitude));
                    GeoDistanceQueryBuilder geoDistanceQueryBuilder =
                            QueryBuilders.geoDistanceQuery("location")
                                    //距离 500KM
                                    .distance(500D, DistanceUnit.KILOMETERS)
                                    //坐标
                                    .point(geoPoint);
                    boolQueryBuilder.must(geoDistanceQueryBuilder);
                }
            } else {
                boolQueryBuilder.filter(QueryBuilders.termQuery("source", source));
                //后台查询，前登录人来显示文章
//                UserPrinciple loginUser = LbsSecurityContenxt.getLoginToken();
//                if (loginUser != null && Roles.SHOP.equals(loginUser.getRole())) {
//                    boolQueryBuilder.must(QueryBuilders.termQuery("userId", loginUser.getId()));
//                }
            }
        }
        //分页显示
        int page = articleQuery.getPageNo();
        int size = articleQuery.getPageSize();
        int from = (page - 1) * size;
        searchSourceBuilder.from(from);
        searchSourceBuilder.size(size);

        // 添加排序
        SortBuilder<?> sortBuilder = SortBuilders.fieldSort("updateTime")
            .order(SortOrder.DESC); // 根据需要更改排序字段和顺序
        searchSourceBuilder.sort(sortBuilder);
        searchSourceBuilder.query(boolQueryBuilder);
        searchRequest.source(searchSourceBuilder);
        SearchResponse reponse = null;
        try {
            reponse = client.search(searchRequest, RequestOptions.DEFAULT);
            //总条数
            long total = reponse.getHits().getTotalHits().value;

            //返回值封装
            List<ArticleContentDTO> list = new ArrayList<>();
            for (SearchHit searchHit : reponse.getHits().getHits()) {
                Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();
                ArticleContentDTO articleContentDTO = JSON.parseObject(JSON.toJSONString(sourceAsMap), ArticleContentDTO.class);
                articleContentDTO.setId(searchHit.getId());

                //查询用户头像和名称，建议采用list一次查询
                if (articleContentDTO.getSource() == 1) {
                    UserVO userVO = userGroupApi.getUser(articleContentDTO.getUserId());
                    articleContentDTO.setUserName(userVO.getUserName());
                    articleContentDTO.setUserPic(userVO.getUserNickPicture());
                } else {
                    BusinessVO busiStoreVO = userGroupApi.businessDetail(articleContentDTO.getUserId());
                    articleContentDTO.setUserName(busiStoreVO == null ? "" : busiStoreVO.getBusinessName());
                }
                list.add(articleContentDTO);
            }
            PageResult<ArticleContentDTO> pageResult = new PageResult<>();
            pageResult.setTotal(total);
            pageResult.setPageNo(page);
            pageResult.setPageSize(size);
            pageResult.setObjects(list);
            return pageResult;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void behavior(ArticleActionParam articleActionParam) throws BusinessException {
        //todo 获取当前登陆人
        UserPrinciple loginUser = LbsSecurityContenxt.getLoginToken();
        log.info("behavior loginUser = {}", JSONObject.toJSONString(loginUser));
        UserVO userVO = userGroupApi.getUser(loginUser.getId());
        String id = articleActionParam.getId();
        //获取文章详情
        ArticleContentDTO articleContentDTO = get(id);
        //文章发布者id
        Integer userId = articleContentDTO.getUserId();

        Map<String, Object> map = new HashMap<>();
        //文章id
        map.put("articleId", id);
        map.put("articleTitle", articleContentDTO.getArticleTitle());
        //点赞人 收藏人或者评论人
        map.put("likePerson", loginUser.getId());
        //被点赞人 收藏人或者评论人
        map.put("likedPerson", userId);
        map.put("createTime", DateUtil.format(new Date(), DatePattern.NORM_DATETIME_FORMAT));
        map.put("comment", articleActionParam.getComment());
        //1==赞  2==收藏  3==评论
        map.put("behavior", articleActionParam.getBehavior());

        IndexRequest indexRequest = new IndexRequest(Const.ACTION_INDEX_DATABASE_NAME).id(UUID.randomUUID().toString().replaceAll("-", ""));
        indexRequest.source(map);
        try {
            client.index(indexRequest, RequestOptions.DEFAULT);

            String userAction = "";
            if (articleActionParam.getBehavior() == 1) {
                userAction = "点赞";
            } else {
                userAction = "收藏";
            }
            RegisterTriggerMessageParam triggerMessageParam = new RegisterTriggerMessageParam();
            triggerMessageParam.setUserId(String.valueOf(articleContentDTO.getUserId()));
            triggerMessageParam.setUserAction(userAction);
            triggerMessageParam.setUsername(userVO.getNickName());
            triggerMessageParam.setArticleId(articleContentDTO.getId());
            triggerMessageParam.setArticleTitle(articleContentDTO.getArticleTitle());
            triggerMessageApi.sendMessage(triggerMessageParam);
        } catch (IOException e) {
            log.error("ArticleServiceImpl.insert es插入失败：", e.getMessage());
            throw new RuntimeException(e);
        }

    }

    @Override
    public ArticleActionPageResultDTO getCurrentUserBehavior(BasePageQuery pageQuery) {
        //todo 获取当前登陆人
        UserPrinciple loginUser = LbsSecurityContenxt.getLoginToken();
        if(ObjectUtils.isEmpty(loginUser)){
            return null;
        }
        Integer currentUserId = loginUser.getId();
        //点赞数据
        CompletableFuture<PageResult<ArticleActionDTO>> likeFuture =
                CompletableFuture.supplyAsync(() -> selectByAction(pageQuery, 1, currentUserId));

        //收藏数据
        CompletableFuture<PageResult<ArticleActionDTO>> collectFuture =
                CompletableFuture.supplyAsync(() -> selectByAction(pageQuery, 2, currentUserId));

        //评论数据
        CompletableFuture<PageResult<ArticleActionDTO>> commentFuture =
                CompletableFuture.supplyAsync(() -> selectByAction(pageQuery, 3, currentUserId));

        CompletableFuture<Void> allFutures = CompletableFuture.allOf(likeFuture, collectFuture, commentFuture);

        try {
            allFutures.get(); // 等待所有 CompletableFuture 完成
            PageResult<ArticleActionDTO> likeFuturePageResult = likeFuture.get();
            PageResult<ArticleActionDTO> collectFutureOPageResult = collectFuture.get();
            PageResult<ArticleActionDTO> commentFuturePageResult = commentFuture.get();
            ArticleActionPageResultDTO articleActionPageResultDTO = new ArticleActionPageResultDTO();
            articleActionPageResultDTO.setLikeFuturePageResult(likeFuturePageResult);
            articleActionPageResultDTO.setCollectFutureOPageResult(collectFutureOPageResult);
            articleActionPageResultDTO.setCommentFuturePageResult(commentFuturePageResult);
            return articleActionPageResultDTO;
        } catch (Exception e) {
            log.error("getCurrentUserBehavior e={}",e);
            throw new RuntimeException(e);
        }
    }


    private PageResult<ArticleActionDTO> selectByAction(BasePageQuery pageQuery, Integer behavior, Integer currentUserId) {
        //构造查询条件
        SearchRequest searchRequest = new SearchRequest(Const.ACTION_INDEX_DATABASE_NAME);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        //条件查询，条件拼接
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.filter(QueryBuilders.termQuery("behavior", behavior));
        boolQueryBuilder.filter(QueryBuilders.termQuery("likePerson", currentUserId));

        int page = pageQuery.getPageNo();
        int size = pageQuery.getPageSize();
        int from = (page - 1) * size;
        searchSourceBuilder.from(from);
        searchSourceBuilder.size(size);

        // 添加排序
        SortBuilder<?> sortBuilder = SortBuilders.fieldSort("createTime")
            .order(SortOrder.DESC); // 根据需要更改排序字段和顺序
        searchSourceBuilder.sort(sortBuilder);
        searchSourceBuilder.query(boolQueryBuilder);
        searchRequest.source(searchSourceBuilder);
        SearchResponse reponse = null;
        try {
            reponse = client.search(searchRequest, RequestOptions.DEFAULT);
            //总条数
            long total = reponse.getHits().getTotalHits().value;
            //返回值封装
            List<ArticleActionDTO> list = new ArrayList<>();

            for (SearchHit searchHit : reponse.getHits().getHits()) {
                Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();
                ArticleActionDTO articleActionDTO = JSON.parseObject(JSON.toJSONString(sourceAsMap), ArticleActionDTO.class);
                articleActionDTO.setId(searchHit.getId());
                //todo 根据用户id获取用户头像
                String likePerson = articleActionDTO.getLikePerson();

                String articleId = articleActionDTO.getArticleId();
                ArticleContentDTO articleContentDTO = get(articleId);
                String articleCover = articleContentDTO.getArticleCover();
                articleActionDTO.setArticleCover(articleCover);
                list.add(articleActionDTO);
            }
            PageResult<ArticleActionDTO> pageResult = new PageResult<>();
            pageResult.setTotal(total);
            pageResult.setPageNo(page);
            pageResult.setPageSize(size);
            pageResult.setObjects(list);
            return pageResult;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (BusinessException e) {
            throw new RuntimeException(e);
        }
    }
}
